package httputil

import (
	"bytes"
	"encoding/json"
	"github.com/cihub/seelog"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

// ToQueryStr @return eg: k1=v1&k2=v2
func ToQueryStr(params map[string]string) string {
	if params == nil || len(params) == 0 {
		return ""
	}
	buf := strings.Builder{}
	for k, v := range params {
		if buf.Len() > 0 {
			buf.WriteString("&")
		}
		buf.WriteString(k)
		buf.WriteString("=")
		buf.WriteString(v)
	}
	return buf.String()
}

func Get(url string) string {
	resp, err := http.Get(url)
	if err != nil {
		seelog.Errorf("fail to http Get, err:%v", err)
		return ""
	}
	defer resp.Body.Close()
	return readAllStr(resp.Body)
}

func PostJson(url string, jsonParams interface{}) string {
	arr, err := json.Marshal(jsonParams)
	if err != nil {
		seelog.Errorf("fail to marshal jsonParams when http json, err: %v, jsonParams:%s", err, jsonParams)
		return ""
	}

	params := bytes.NewBuffer(arr)
	resp, err := http.Post(url, "application/json; charset=utf-8", params)
	if err != nil {
		seelog.Errorf("fail to http.Post, err: %v", err)
		return ""
	}
	defer resp.Body.Close()
	return readAllStr(resp.Body)
}

func PostXWwwFormUrlEncoded(url, strParams string) string {
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(strParams))
	if err != nil {
		seelog.Errorf("fail to http Post, err:%v", err)
		return ""
	}
	defer resp.Body.Close()
	return readAllStr(resp.Body)
}

func readAllStr(r io.Reader) string {
	arr, err := ioutil.ReadAll(r)
	if err != nil {
		seelog.Errorf("fail to readAll, err:%v", err)
		return ""
	}
	return string(arr)
}
